package com.tiandy.flow.flowserver.demos.web.utils;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

/**
 * 图形数据转换器 - 将序列化的JSON数据转换为对象树结构
 */
public class GraphDataConverter {
    
    /**
     * 主数据容器类
     */
    public static class GraphDataContainer {
        private GraphData graph;
        private Map<String, Object> businessData;
        
        public GraphDataContainer() {}
        
        public GraphDataContainer(GraphData graph, Map<String, Object> businessData) {
            this.graph = graph;
            this.businessData = businessData;
        }
        
        public GraphData getGraph() { return graph; }
        public void setGraph(GraphData graph) { this.graph = graph; }
        public Map<String, Object> getBusinessData() { return businessData; }
        public void setBusinessData(Map<String, Object> businessData) { this.businessData = businessData; }
    }
    
    /**
     * 图形数据结构
     */
    public static class GraphData {
        private List<CellData> cells;
        private Map<String, Object> options;
        
        public GraphData() {}
        
        public GraphData(List<CellData> cells, Map<String, Object> options) {
            this.cells = cells;
            this.options = options;
        }
        
        public List<CellData> getCells() { return cells; }
        public void setCells(List<CellData> cells) { this.cells = cells; }
        public Map<String, Object> getOptions() { return options; }
        public void setOptions(Map<String, Object> options) { this.options = options; }
    }
    
    /**
     * 单元格数据（节点或边）
     */
    public static class CellData {
        private String id;
        private String shape;
        private String type;
        private Position position;
        private Size size;
        private Map<String, Object> attrs;
        private Map<String, Object> data;
        private PortsData ports;
        private List<String> children;
        private String parent;
        private Map<String, Object> markup;
        private Integer zIndex;
        
        public CellData() {}
        
        public String getId() { return id; }
        public void setId(String id) { this.id = id; }
        public String getShape() { return shape; }
        public void setShape(String shape) { this.shape = shape; }
        public String getType() { return type; }
        public void setType(String type) { this.type = type; }
        public Position getPosition() { return position; }
        public void setPosition(Position position) { this.position = position; }
        public Size getSize() { return size; }
        public void setSize(Size size) { this.size = size; }
        public Map<String, Object> getAttrs() { return attrs; }
        public void setAttrs(Map<String, Object> attrs) { this.attrs = attrs; }
        public Map<String, Object> getData() { return data; }
        public void setData(Map<String, Object> data) { this.data = data; }
        public PortsData getPorts() { return ports; }
        public void setPorts(PortsData ports) { this.ports = ports; }
        public List<String> getChildren() { return children; }
        public void setChildren(List<String> children) { this.children = children; }
        public String getParent() { return parent; }
        public void setParent(String parent) { this.parent = parent; }
        public Map<String, Object> getMarkup() { return markup; }
        public void setMarkup(Map<String, Object> markup) { this.markup = markup; }
        public Integer getZIndex() { return zIndex; }
        public void setZIndex(Integer zIndex) { this.zIndex = zIndex; }
    }
    
    /**
     * 位置信息
     */
    public static class Position {
        private double x;
        private double y;
        
        public Position() {}
        
        public Position(double x, double y) {
            this.x = x;
            this.y = y;
        }
        
        public double getX() { return x; }
        public void setX(double x) { this.x = x; }
        public double getY() { return y; }
        public void setY(double y) { this.y = y; }
    }
    
    /**
     * 尺寸信息
     */
    public static class Size {
        private double width;
        private double height;
        
        public Size() {}
        
        public Size(double width, double height) {
            this.width = width;
            this.height = height;
        }
        
        public double getWidth() { return width; }
        public void setWidth(double width) { this.width = width; }
        public double getHeight() { return height; }
        public void setHeight(double height) { this.height = height; }
    }

    /**
     * 端口组信息
     */
    public static class PortGroup {
        private String position;
        private Map<String, Object> attrs;
        
        public PortGroup() {}
        
        public String getPosition() { return position; }
        public void setPosition(String position) { this.position = position; }
        public Map<String, Object> getAttrs() { return attrs; }
        public void setAttrs(Map<String, Object> attrs) { this.attrs = attrs; }
    }

    /**
     * 端口项信息
     */
    public static class PortItem {
        private String group;
        private String id;
        private Map<String, Object> attrs;
        
        public PortItem() {}
        
        public String getGroup() { return group; }
        public void setGroup(String group) { this.group = group; }
        public String getId() { return id; }
        public void setId(String id) { this.id = id; }
        public Map<String, Object> getAttrs() { return attrs; }
        public void setAttrs(Map<String, Object> attrs) { this.attrs = attrs; }
    }

    /**
     * 端口数据结构
     */
    public static class PortsData {
        private Map<String, PortGroup> groups;
        private List<PortItem> items;
        
        public PortsData() {}
        
        public Map<String, PortGroup> getGroups() { return groups; }
        public void setGroups(Map<String, PortGroup> groups) { this.groups = groups; }
        public List<PortItem> getItems() { return items; }
        public void setItems(List<PortItem> items) { this.items = items; }
    }

    /**
     * 将JSON字符串转换为对象树结构
     */
    public GraphDataContainer convertFromJson(String jsonString) throws IOException {
        // 简单的JSON解析实现
        GraphDataContainer container = new GraphDataContainer();
        
        // 解析JSON字符串
        Map<String, Object> rootMap = parseJson(jsonString);
        
        // 解析graph部分
        if (rootMap.containsKey("graph")) {
            Object graphObj = rootMap.get("graph");
            if (graphObj instanceof Map) {
                Map<String, Object> graphMap = (Map<String, Object>) graphObj;
                GraphData graphData = new GraphData();
                
                // 解析cells
                if (graphMap.containsKey("cells")) {
                    Object cellsObj = graphMap.get("cells");
                    if (cellsObj instanceof List) {
                        List<Object> cellsList = (List<Object>) cellsObj;
                        List<CellData> cells = new ArrayList<>();
                        
                        for (Object cellObj : cellsList) {
                            if (cellObj instanceof Map) {
                                Map<String, Object> cellMap = (Map<String, Object>) cellObj;
                                CellData cellData = parseCellData(cellMap);
                                cells.add(cellData);
                            }
                        }
                        graphData.setCells(cells);
                    }
                }
                
                // 解析options
                if (graphMap.containsKey("options")) {
                    Object optionsObj = graphMap.get("options");
                    if (optionsObj instanceof Map) {
                        graphData.setOptions((Map<String, Object>) optionsObj);
                    }
                }
                
                container.setGraph(graphData);
            }
        }
        
        // 解析businessData部分
        if (rootMap.containsKey("businessData")) {
            Object businessDataObj = rootMap.get("businessData");
            if (businessDataObj instanceof Map) {
                container.setBusinessData((Map<String, Object>) businessDataObj);
            }
        }
        
        return container;
    }
    
    /**
     * 简单的JSON解析器
     */
    private Map<String, Object> parseJson(String jsonString) {
        Map<String, Object> result = new HashMap<>();
        jsonString = jsonString.trim();
        
        if (jsonString.startsWith("{") && jsonString.endsWith("}")) {
            jsonString = jsonString.substring(1, jsonString.length() - 1);
            String[] pairs = splitJsonPairs(jsonString);
            
            for (String pair : pairs) {
                String[] keyValue = pair.split(":", 2);
                if (keyValue.length == 2) {
                    String key = keyValue[0].trim().replaceAll("^\"|\"$", "");
                    Object value = parseJsonValue(keyValue[1].trim());
                    result.put(key, value);
                }
            }
        }
        
        return result;
    }
    
    /**
     * 解析JSON值
     */
    private Object parseJsonValue(String valueStr) {
        if (valueStr.startsWith("\"") && valueStr.endsWith("\"")) {
            return valueStr.substring(1, valueStr.length() - 1);
        } else if (valueStr.equals("true")) {
            return true;
        } else if (valueStr.equals("false")) {
            return false;
        } else if (valueStr.equals("null")) {
            return null;
        } else if (valueStr.matches("-?\\d+(\\.\\d+)?")) {
            if (valueStr.contains(".")) {
                return Double.parseDouble(valueStr);
            } else {
                return Integer.parseInt(valueStr);
            }
        } else if (valueStr.startsWith("[") && valueStr.endsWith("]")) {
            return parseJsonArray(valueStr);
        } else if (valueStr.startsWith("{") && valueStr.endsWith("}")) {
            return parseJson(valueStr);
        }
        return valueStr;
    }
    
    /**
     * 解析JSON数组
     */
    private List<Object> parseJsonArray(String arrayStr) {
        List<Object> result = new ArrayList<>();
        arrayStr = arrayStr.substring(1, arrayStr.length() - 1);
        
        if (arrayStr.trim().isEmpty()) {
            return result;
        }
        
        String[] elements = splitJsonArray(arrayStr);
        for (String element : elements) {
            result.add(parseJsonValue(element.trim()));
        }
        
        return result;
    }
    
    /**
     * 分割JSON对象对
     */
    private String[] splitJsonPairs(String jsonStr) {
        List<String> pairs = new ArrayList<>();
        int braceCount = 0;
        int bracketCount = 0;
        int start = 0;
        boolean inString = false;
        
        for (int i = 0; i < jsonStr.length(); i++) {
            char c = jsonStr.charAt(i);
            
            if (c == '"' && (i == 0 || jsonStr.charAt(i - 1) != '\\')) {
                inString = !inString;
            } else if (!inString) {
                if (c == '{') braceCount++;
                else if (c == '}') braceCount--;
                else if (c == '[') bracketCount++;
                else if (c == ']') bracketCount--;
                else if (c == ',' && braceCount == 0 && bracketCount == 0) {
                    pairs.add(jsonStr.substring(start, i));
                    start = i + 1;
                }
            }
        }
        
        if (start < jsonStr.length()) {
            pairs.add(jsonStr.substring(start));
        }
        
        return pairs.toArray(new String[0]);
    }
    
    /**
     * 分割JSON数组元素
     */
    private String[] splitJsonArray(String arrayStr) {
        List<String> elements = new ArrayList<>();
        int braceCount = 0;
        int bracketCount = 0;
        int start = 0;
        boolean inString = false;
        
        for (int i = 0; i < arrayStr.length(); i++) {
            char c = arrayStr.charAt(i);
            
            if (c == '"' && (i == 0 || arrayStr.charAt(i - 1) != '\\')) {
                inString = !inString;
            } else if (!inString) {
                if (c == '{') braceCount++;
                else if (c == '}') braceCount--;
                else if (c == '[') bracketCount++;
                else if (c == ']') bracketCount--;
                else if (c == ',' && braceCount == 0 && bracketCount == 0) {
                    elements.add(arrayStr.substring(start, i));
                    start = i + 1;
                }
            }
        }
        
        if (start < arrayStr.length()) {
            elements.add(arrayStr.substring(start));
        }
        
        return elements.toArray(new String[0]);
    }
    
    /**
     * 解析单元格数据
     */
    private CellData parseCellData(Map<String, Object> cellMap) {
        CellData cellData = new CellData();
        
        if (cellMap.containsKey("id")) {
            cellData.setId(cellMap.get("id").toString());
        }
        if (cellMap.containsKey("shape")) {
            cellData.setShape(cellMap.get("shape").toString());
        }
        if (cellMap.containsKey("type")) {
            cellData.setType(cellMap.get("type").toString());
        }
        if (cellMap.containsKey("parent")) {
            cellData.setParent(cellMap.get("parent").toString());
        }
        if (cellMap.containsKey("zIndex")) {
            Object zIndexObj = cellMap.get("zIndex");
            if (zIndexObj instanceof Number) {
                cellData.setZIndex(((Number) zIndexObj).intValue());
            }
        }
        
        // 解析position
        if (cellMap.containsKey("position")) {
            Object posObj = cellMap.get("position");
            if (posObj instanceof Map) {
                Map<String, Object> posMap = (Map<String, Object>) posObj;
                Position position = new Position();
                if (posMap.containsKey("x")) {
                    position.setX(((Number) posMap.get("x")).doubleValue());
                }
                if (posMap.containsKey("y")) {
                    position.setY(((Number) posMap.get("y")).doubleValue());
                }
            cellData.setPosition(position);
            }
        }
        
        // 解析size
        if (cellMap.containsKey("size")) {
            Object sizeObj = cellMap.get("size");
            if (sizeObj instanceof Map) {
                Map<String, Object> sizeMap = (Map<String, Object>) sizeObj;
                Size size = new Size();
                if (sizeMap.containsKey("width")) {
                    size.setWidth(((Number) sizeMap.get("width")).doubleValue());
                }
                if (sizeMap.containsKey("height")) {
                    size.setHeight(((Number) sizeMap.get("height")).doubleValue());
                }
            cellData.setSize(size);
            }
        }
        
        // 解析attrs
        if (cellMap.containsKey("attrs")) {
            Object attrsObj = cellMap.get("attrs");
            if (attrsObj instanceof Map) {
                cellData.setAttrs((Map<String, Object>) attrsObj);
            }
        }
        
        // 解析data
        Map<String, Object> dataMap = new HashMap<>();
        if (cellMap.containsKey("data")) {
            Object dataObj = cellMap.get("data");
            if (dataObj instanceof Map) {
                dataMap.putAll((Map<String, Object>) dataObj);
            }
        }
        
        // 对于边，将根级别的source和target字段添加到data中
        if ("edge".equals(cellData.getShape())) {
            if (cellMap.containsKey("source")) {
                dataMap.put("source", cellMap.get("source"));
            }
            if (cellMap.containsKey("target")) {
                dataMap.put("target", cellMap.get("target"));
            }
        }
        
        cellData.setData(dataMap);
        
        // 解析children
        if (cellMap.containsKey("children")) {
            Object childrenObj = cellMap.get("children");
            if (childrenObj instanceof List) {
                List<Object> childrenList = (List<Object>) childrenObj;
                List<String> children = new ArrayList<>();
                for (Object child : childrenList) {
                    children.add(child.toString());
            }
            cellData.setChildren(children);
        }
        }
        
        return cellData;
    }
    
    /**
     * 将JSON文件转换为对象树结构
     */
    public GraphDataContainer convertFromFile(String filePath) throws IOException {
        String content = new String(Files.readAllBytes(Paths.get(filePath)));
        return convertFromJson(content);
    }

    /**
     * 根据端口连线关系生成依赖排序列表
     * 要求：
     * 1. 组内的元素不参与，只有组参与排序
     * 2. 开始节点一定在最开始
     * 3. 结束节点一定在最后
     */
    public List<CellData> generateDependencyOrderedList(GraphDataContainer container) {
        if (container == null || container.getGraph() == null || container.getGraph().getCells() == null) {
            return new ArrayList<>();
        }

        List<CellData> cells = container.getGraph().getCells();
        
        // 分离节点和边
        List<CellData> nodes = new ArrayList<>();
        List<CellData> edges = new ArrayList<>();
        
        for (CellData cell : cells) {
            if ("edge".equals(cell.getShape())) {
                edges.add(cell);
            } else {
                // 忽略 isPlusIcon 为 true 的节点
                if (!isPlusIcon(cell)) {
                    nodes.add(cell);
                }
            }
        }

        // 找到开始和结束节点
        CellData startNode = null;
        CellData endNode = null;
        List<CellData> groupNodes = new ArrayList<>();
        List<CellData> otherNodes = new ArrayList<>();

        for (CellData node : nodes) {
            String nodeLabel = getNodeLabel(node);
            if ("开始".equals(nodeLabel) || "开始节点".equals(nodeLabel)) {
                startNode = node;
            } else if ("结束".equals(nodeLabel) || "结束节点".equals(nodeLabel)) {
                endNode = node;
            } else if (isGroupNode(node)) {
                groupNodes.add(node);
            } else {
                // 检查是否在组内
                if (!isNodeInGroup(node, nodes)) {
                    otherNodes.add(node);
                }
            }
        }

        // 构建邻接表（只包含组节点和组外节点）
        Map<String, List<String>> adjacencyList = new HashMap<>();
        Map<String, Integer> inDegree = new HashMap<>();
        
        // 初始化
        for (CellData node : groupNodes) {
            adjacencyList.put(node.getId(), new ArrayList<>());
            inDegree.put(node.getId(), 0);
        }
        for (CellData node : otherNodes) {
            adjacencyList.put(node.getId(), new ArrayList<>());
            inDegree.put(node.getId(), 0);
        }
        
        // 根据边构建依赖关系
        for (CellData edge : edges) {
            String sourceId = getEdgeSourceId(edge);
            String targetId = getEdgeTargetId(edge);
            
            if (sourceId != null && targetId != null) {
                // 找到源节点（从所有节点中查找，包括开始节点和组内节点）
                CellData sourceNode = findNodeById(sourceId, nodes);
                
                if (sourceNode != null) {
                    // 检查源节点是否参与排序
                    CellData sourceNodeForSort = findNodeById(sourceId, groupNodes, otherNodes);
                    
                    if (sourceNodeForSort != null) {
                        // 检查目标节点是否在组内
                        CellData actualTargetNode = findNodeById(targetId, nodes);
                        if (actualTargetNode != null && isNodeInGroup(actualTargetNode, nodes)) {
                            // 如果目标节点在组内，则源节点应该依赖组节点
                            CellData groupNode = findGroupNodeForChild(actualTargetNode, nodes);
                            if (groupNode != null) {
                                adjacencyList.get(sourceNodeForSort.getId()).add(groupNode.getId());
                                inDegree.put(groupNode.getId(), inDegree.get(groupNode.getId()) + 1);
                            }
                        } else {
                            // 目标节点不在组内，检查是否参与排序
                            CellData targetNode = findNodeById(targetId, groupNodes, otherNodes);
                            if (targetNode != null) {
                                adjacencyList.get(sourceNodeForSort.getId()).add(targetNode.getId());
                                inDegree.put(targetNode.getId(), inDegree.get(targetNode.getId()) + 1);
                            }
                        }
                    } else {
                        // 源节点不参与排序（如开始节点、组内节点等）
                        // 检查目标节点是否参与排序
                        CellData targetNode = findNodeById(targetId, groupNodes, otherNodes);
                        if (targetNode != null) {
                            // 如果源节点是组内节点，目标节点应该依赖组节点
                            CellData sourceGroupNode = findGroupNodeForChild(sourceNode, nodes);
                            if (sourceGroupNode != null) {
                                adjacencyList.get(sourceGroupNode.getId()).add(targetNode.getId());
                                inDegree.put(targetNode.getId(), inDegree.get(targetNode.getId()) + 1);
                            }
                        }
                    }
                }
            }
        }

        // 拓扑排序
        List<CellData> orderedNodes = new ArrayList<>();
        Queue<String> queue = new LinkedList<>();
        
        // 将入度为0的节点加入队列
        for (Map.Entry<String, Integer> entry : inDegree.entrySet()) {
            if (entry.getValue() == 0) {
                queue.offer(entry.getKey());
            }
        }

        // 执行拓扑排序
        while (!queue.isEmpty()) {
            String nodeId = queue.poll();
            CellData node = findNodeById(nodeId, groupNodes, otherNodes);
            if (node != null) {
                orderedNodes.add(node);
            }

            // 更新邻接节点的入度
            List<String> neighbors = adjacencyList.get(nodeId);
            if (neighbors != null) {
                for (String neighborId : neighbors) {
                    inDegree.put(neighborId, inDegree.get(neighborId) - 1);
                    if (inDegree.get(neighborId) == 0) {
                        queue.offer(neighborId);
                    }
                }
            }
        }

        // 构建最终结果：开始节点 + 排序后的节点 + 结束节点
        List<CellData> result = new ArrayList<>();
        if (startNode != null) {
            result.add(startNode);
        }
        result.addAll(orderedNodes);
        if (endNode != null) {
            result.add(endNode);
        }

        return result;
    }

    /**
     * 获取节点标签
     */
    private String getNodeLabel(CellData node) {
        if (node.getAttrs() != null && node.getAttrs().containsKey("label")) {
            Object labelObj = node.getAttrs().get("label");
            if (labelObj instanceof Map) {
                Map<String, Object> labelMap = (Map<String, Object>) labelObj;
                if (labelMap.containsKey("text")) {
                    return labelMap.get("text").toString();
                }
            }
        }
        return "";
    }

    /**
     * 检查节点是否在组内
     */
    private boolean isNodeInGroup(CellData node, List<CellData> allNodes) {
        if (node.getParent() != null) {
            // 检查父节点是否是组节点
            for (CellData parentNode : allNodes) {
                if (parentNode.getId().equals(node.getParent())) {
                    return isGroupNode(parentNode);
                }
            }
        }
        return false;
    }

    /**
     * 获取边的源节点ID
     */
    private String getEdgeSourceId(CellData edge) {
        // 检查根级别的source字段（这是JSON中的实际结构）
        // 注意：在CellData中，根级别的字段会被映射到data字段
        if (edge.getData() != null && edge.getData().containsKey("source")) {
            Object sourceObj = edge.getData().get("source");
            if (sourceObj instanceof Map) {
                Map<String, Object> sourceMap = (Map<String, Object>) sourceObj;
                if (sourceMap.containsKey("cell")) {
                    return sourceMap.get("cell").toString();
                }
            }
        }
        return null;
    }

    /**
     * 获取边的目标节点ID
     */
    private String getEdgeTargetId(CellData edge) {
        // 检查根级别的target字段（这是JSON中的实际结构）
        // 注意：在CellData中，根级别的字段会被映射到data字段
        if (edge.getData() != null && edge.getData().containsKey("target")) {
            Object targetObj = edge.getData().get("target");
            if (targetObj instanceof Map) {
                Map<String, Object> targetMap = (Map<String, Object>) targetObj;
                if (targetMap.containsKey("cell")) {
                    return targetMap.get("cell").toString();
                }
            }
        }
        return null;
    }

    /**
     * 检查节点是否为加号图标
     */
    private boolean isPlusIcon(CellData node) {
        if (node.getData() != null && node.getData().containsKey("isPlusIcon")) {
            Object isPlusIcon = node.getData().get("isPlusIcon");
            return isPlusIcon instanceof Boolean && (Boolean) isPlusIcon;
        }
        return false;
    }

    /**
     * 检查节点是否为组节点
     */
    private boolean isGroupNode(CellData node) {
        // 检查 data.type 是否为 "group"
        if (node.getData() != null && node.getData().containsKey("type")) {
            Object type = node.getData().get("type");
            return "group".equals(type);
        }
        // 兼容旧格式：检查 shape 或 type 字段
        return "group".equals(node.getShape()) || "group".equals(node.getType());
    }

    /**
     * 根据ID查找节点
     */
    private CellData findNodeById(String nodeId, List<CellData> groupNodes, List<CellData> otherNodes) {
        for (CellData node : groupNodes) {
            if (node.getId().equals(nodeId)) {
                return node;
            }
        }
        for (CellData node : otherNodes) {
            if (node.getId().equals(nodeId)) {
                return node;
            }
        }
        return null;
    }

    /**
     * 根据ID查找节点（从所有节点中查找）
     */
    private CellData findNodeById(String nodeId, List<CellData> allNodes) {
        for (CellData node : allNodes) {
            if (node.getId().equals(nodeId)) {
                return node;
            }
        }
        return null;
    }

    /**
     * 查找子节点所属的组节点
     */
    private CellData findGroupNodeForChild(CellData childNode, List<CellData> allNodes) {
        if (childNode.getParent() != null) {
            return findNodeById(childNode.getParent(), allNodes);
        }
        return null;
    }

    /**
     * 打印依赖排序结果
     */
    public void printDependencyOrderedList(GraphDataContainer container) {
        System.out.println("=== 依赖排序结果 ===");
        List<CellData> orderedList = generateDependencyOrderedList(container);
        
        for (int i = 0; i < orderedList.size(); i++) {
            CellData node = orderedList.get(i);
            String label = getNodeLabel(node);
            String type = node.getType() != null ? node.getType() : node.getShape();
            System.out.println((i + 1) + ". " + label + " (ID: " + node.getId() + ", Type: " + type + ")");
        }
    }
    
    /**
     * 获取两个节点之间的节点，按依赖顺序输出
     * @param container 图形数据容器
     * @param startNodeId 开始节点ID
     * @param endNodeId 结束节点ID
     * @return 按依赖顺序排列的节点列表
     */
    public List<CellData> getNodesBetween(GraphDataContainer container, String startNodeId, String endNodeId) {
        // 直接用 generateDependencyOrderedList 得到全局依赖顺序
        List<CellData> ordered = generateDependencyOrderedList(container);
        // 找到 startNode 和 endNode 的下标
        int startIdx = -1, endIdx = -1;
        for (int i = 0; i < ordered.size(); i++) {
            if (ordered.get(i).getId().equals(startNodeId)) {
                startIdx = i;
            }
            if (ordered.get(i).getId().equals(endNodeId)) {
                endIdx = i;
            }
        }
        if (startIdx == -1 || endIdx == -1 || startIdx > endIdx) {
            return new ArrayList<>();
        }
        // 截取 start 到 end 之间的所有节点（含首尾）
        return new ArrayList<>(ordered.subList(startIdx, endIdx + 1));
    }

    /**
     * 使用BFS找到从开始节点到结束节点的所有可达节点（遍历所有路径，不提前break）
     */
    private Set<String> findReachableNodes(CellData startNode, CellData endNode, List<CellData> nodes, List<CellData> edges) {
        Set<String> reachableNodes = new HashSet<>();
        Queue<String> queue = new LinkedList<>();
        Set<String> visited = new HashSet<>();
        // 从开始节点开始BFS
        queue.offer(startNode.getId());
        visited.add(startNode.getId());
        reachableNodes.add(startNode.getId());
        while (!queue.isEmpty()) {
            String currentId = queue.poll();
            // 不提前break，遍历所有路径
            // 查找所有以当前节点为源的边
            for (CellData edge : edges) {
                String sourceId = getEdgeSourceId(edge);
                String targetId = getEdgeTargetId(edge);
                if (sourceId != null && targetId != null && sourceId.equals(currentId)) {
                    if (!visited.contains(targetId)) {
                        visited.add(targetId);
                        reachableNodes.add(targetId);
                        queue.offer(targetId);
                    }
                }
            }
        }
        // 确保结束节点也被包含在内
        reachableNodes.add(endNode.getId());
        return reachableNodes;
    }

    /**
     * 打印两个节点之间的节点列表
     */
    public void printNodesBetween(GraphDataContainer container, String startNodeId, String endNodeId) {
        System.out.println("=== 节点 " + startNodeId + " 到 " + endNodeId + " 之间的节点（按依赖顺序）===");
        List<CellData> nodesBetween = getNodesBetween(container, startNodeId, endNodeId);
        
        if (nodesBetween.isEmpty()) {
            System.out.println("没有找到节点之间的路径");
            return;
        }
        
        for (int i = 0; i < nodesBetween.size(); i++) {
            CellData node = nodesBetween.get(i);
            String label = getNodeLabel(node);
            String type = node.getType() != null ? node.getType() : node.getShape();
            System.out.println((i + 1) + ". " + label + " (ID: " + node.getId() + ", Type: " + type + ")");
        }
    }
    
    /**
     * 主方法 - 使用示例
     */
    public static void main(String[] args) {
        try {
            GraphDataConverter converter = new GraphDataConverter();
            
            // 示例：从文件转换
            GraphDataContainer container = converter.convertFromFile("D:\\个人\\Desktop\\xulie.txt");
            
            // 打印依赖排序结果
            converter.printDependencyOrderedList(container);
            
            // 示例：获取两个节点之间的节点
            System.out.println("\n");
            // 这里需要根据实际的节点ID来调用
            converter.printNodesBetween(container, "b31cea8b-071f-4306-8afe-c2aeb9517ee1", "515f95ee-9777-404d-afef-5d55eedbc67d");
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}